// DeviceVideoAdapter.java
package com.xsq.wifi.adapter;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.xsq.wifi.R;
import com.xsq.wifi.model.DeviceVideoListModel;
import com.xsq.wifi.utils.RoundedCornersTransformation;

import java.io.File;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DeviceVideoAdapter extends RecyclerView.Adapter<DeviceVideoAdapter.ViewHolder> {

    public List<DeviceVideoListModel> deviceVideoListModels;
    private Activity mactivity;
    private int selectedPosition = -1;
    private String selectedVideoName;
    private boolean showProgressForSelected = true;
    private Map<String, Integer> deviceProgressMap = new HashMap<>();
    private static final String PAYLOAD_PROGRESS = "progress_payload";

    static class ViewHolder extends RecyclerView.ViewHolder {
        ImageView video_img, play_status;
        TextView video_name;
        SeekBar seekBar;
        boolean isPlaying = false;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            video_img = itemView.findViewById(R.id.video_img);
            video_name = itemView.findViewById(R.id.video_name);
            play_status = itemView.findViewById(R.id.play_status);
            seekBar = itemView.findViewById(R.id.seekBar);

            // 初始化播放状态
            play_status.setTag("paused");
            play_status.setImageResource(R.mipmap.pause_icon);
        }

        void setSelected(boolean selected) {
            itemView.setBackgroundResource(selected ?
                    R.drawable.white_bg_8dp_andbian :
                    R.drawable.white_bg_8dp);
        }

        void setPlaying(boolean playing) {
            isPlaying = playing;
            play_status.setImageResource(playing ?
                    R.mipmap.play_icon :
                    R.mipmap.pause_icon);
            play_status.setTag(playing ? "playing" : "paused");
        }
    }

    public DeviceVideoAdapter(List<DeviceVideoListModel> lostList, Activity activity) {
        deviceVideoListModels = lostList;
        mactivity = activity;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.device_video_item, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        onBindViewHolder(holder, position, null);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, @SuppressLint("RecyclerView") int position, List<Object> payloads) {
        DeviceVideoListModel model = deviceVideoListModels.get(position);

        // 局部刷新：仅更新进度条
        if (payloads != null && !payloads.isEmpty() && payloads.contains(PAYLOAD_PROGRESS)) {
            Integer progress = deviceProgressMap.get(model.getVideoname());
            if (progress != null) {
                holder.seekBar.setProgress(progress);
            }
            return;
        }

        // 完整绑定
        File file = new File(model.getVideoname());
        String fileName = file.getName();
        String videoName = fileName.substring(0, fileName.lastIndexOf('.'));
        holder.video_name.setText(videoName);

        // 加载封面
        byte[] imageData = ByteBuffer.wrap(model.getVideopath()).array();
        Glide.with(mactivity)
                .load(imageData)
                .transform(new RoundedCornersTransformation(mactivity, 8))
                .into(holder.video_img);

        // 设置选中状态
        boolean isSelected = model.getVideoname().equals(selectedVideoName);
        holder.setSelected(isSelected);

        // 进度条可见性
        holder.seekBar.setVisibility(isSelected ? View.VISIBLE : View.INVISIBLE);
        holder.play_status.setVisibility(isSelected ? View.VISIBLE : View.INVISIBLE);

        // 初始化进度条
        Integer progress = deviceProgressMap.get(model.getVideoname());
        if (progress != null) {
            holder.seekBar.setProgress(progress);
        }

        // 点击事件
        holder.itemView.setOnClickListener(v -> {
//            selectedVideoName = model.getVideoname();
//            notifyItemChanged(selectedPosition);
//            selectedPosition = position;
//            notifyItemChanged(selectedPosition);
//
//            if (mOnItemClickListener != null) {
//                mOnItemClickListener.onItemClick(model.getVideoname());
//            }
        });

        // 替换原来的点击事件
        holder.play_status.setOnClickListener(view -> {
            boolean isPlaying = "playing".equals(view.getTag());

            // 先立即更新UI（提升用户体验）
            holder.setPlaying(!isPlaying);

            if (mOnPlayStatusClickListener != null) {
                // 传递操作类型和回调
                mOnPlayStatusClickListener.onItemClick1(
                        isPlaying ? "1" : "0", // "0"=暂停，"1"=播放
                        new OnStatusUpdateCallback() {
                            @Override
                            public void onSuccess() {
                                // 服务器确认成功，无需处理（UI已更新）
                                Log.v("TAG", "操作成功");
                            }
                            @Override
                            public void onFailure() {
                                // 服务器操作失败，回滚UI状态
                                mactivity.runOnUiThread(() -> {
                                    holder.setPlaying(isPlaying); // 恢复原状态
                                    Log.e("TAG", "操作失败");
                                });
                            }
                        }
                );
            }
        });
    }

    // 设置选中的视频并移动到首位
    public void setSelectedVideo(String videoName, boolean showProgress) {
        int position = -1;
        for (int i = 0; i < deviceVideoListModels.size(); i++) {
            if (deviceVideoListModels.get(i).getVideoname().equals(videoName)) {
                position = i;
                break;
            }
        }
        if (position == -1) return;

        this.selectedVideoName = videoName;
        this.showProgressForSelected = showProgress;

        // 移动到首位
        DeviceVideoListModel selectedItem = deviceVideoListModels.remove(position);
        deviceVideoListModels.add(0, selectedItem);

        // 刷新列表
        notifyItemMoved(position, 0);
        selectedPosition = 0;
        notifyItemChanged(0);
        if (position != 0) {
            notifyItemChanged(position);
        }
    }

    // 更新选中的视频（不移动位置）
    public void updateSelectedVideo(String videoName) {
        int position = -1;
        for (int i = 0; i < deviceVideoListModels.size(); i++) {
            if (deviceVideoListModels.get(i).getVideoname().equals(videoName)) {
                position = i;
                break;
            }
        }
        if (position == -1) return;

        notifyItemChanged(selectedPosition);
        selectedVideoName = videoName;
        selectedPosition = position;
        notifyItemChanged(selectedPosition);
    }

    // 选择下一个视频（不置顶）
    public void selectNextVideo() {
        if (selectedPosition == -1 || deviceVideoListModels.isEmpty()) return;

        int nextPosition = (selectedPosition + 1) % deviceVideoListModels.size();
        selectedVideoName = deviceVideoListModels.get(nextPosition).getVideoname();

        notifyItemChanged(selectedPosition);
        selectedPosition = nextPosition;
        notifyItemChanged(selectedPosition);

        if (mOnItemClickListener != null) {
            mOnItemClickListener.onItemClick(selectedVideoName);
        }
    }

    public void updateDeviceProgress(String deviceName, int progress) {
        deviceProgressMap.put(deviceName, progress);

        int position = -1;
        for (int i = 0; i < deviceVideoListModels.size(); i++) {
            if (deviceVideoListModels.get(i).getVideoname().equals(deviceName)) {
                position = i;
                break;
            }
        }
        if (position == -1) return;

        notifyItemChanged(position, PAYLOAD_PROGRESS);
    }

    public String getSelectedVideoName() {
        return selectedVideoName;
    }

    @Override
    public int getItemCount() {
        return deviceVideoListModels.size();
    }

    private OnItemClickListener mOnItemClickListener;
    private OnItemClickListener1 mOnPlayStatusClickListener;

    public void setOnItemClickListener(OnItemClickListener listener) {
        this.mOnItemClickListener = listener;
    }

    public void setOnPlayStatusClickListener(OnItemClickListener1 listener) {
        this.mOnPlayStatusClickListener = listener;
    }

    public interface OnItemClickListener {
        void onItemClick(String path);
    }

    public interface OnItemClickListener1 {
        void onItemClick1(String isplay,OnStatusUpdateCallback callback);
    }

    // 新增回调接口
    public interface OnStatusUpdateCallback {
        void onSuccess();
        void onFailure();
    }
}